package com.tanhua.server.interceptor;

import com.tanhua.commons.utils.JwtUtils;
import com.tanhua.model.db.User;
import io.jsonwebtoken.Claims;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * preHandle ：前置方法，进入controller之前
 * 返回值：
 *   true：验证通过，进入到controller
 *   false：不通过，返回
 * 业务：判断用户请求的token，是否正确
 */
//自定义拦截器
public class TokenInterceptor implements HandlerInterceptor {

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        String token = request.getHeader("Authorization");
        //判断token是否可以
//        boolean vertifytoken = JwtUtils.verifyToken(token);
//        if(!vertifytoken){
//            response.setStatus(401);
//            return false;
//        }
        //构造user对象传入threadlocal，存入了直接getUserId就能从local里获得id
        Claims claims = JwtUtils.getClaims(token);
        Long id = claims.get("id", Long.class);
        String mobile = claims.get("mobile", String.class);
        //存入local
        User user = new User();
        user.setId(id);
        user.setMobile(mobile);
        UserHolder.setUser(user);
        return true;
    }


    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {

    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {

    }
}
